package org.jeecg.modules.saobei;

import com.alibaba.fastjson.JSON;
import com.saobei.open.sdk.DefaultSaobeiApiClient;
import com.saobei.open.sdk.SaobeiApiClient;
import com.saobei.open.sdk.model.requst.trade.*;
import com.saobei.open.sdk.model.requst.trade.wechat.WxAuthOpenidRequest;
import com.saobei.open.sdk.model.response.trade.*;
import com.saobei.open.sdk.util.ApiConstants;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.util.JSONUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.lcpay.entity.PayReturn;
import org.jeecg.modules.system.service.ISysDataLogService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class Saobei {
    public static final String PAY_VER = "110";//版本号
    public static final String KEY = "28ea7ab4fdfa4c438f29c169f4062fce";//机构秘钥,扫呗分配
    public static final String ACCESS_TOKEN = "0465e934c65243f2955c9508248fb067";//支付秘钥,扫呗分配
    public static final String INST_NO = "10000172";//机构号,扫呗分配
    public static final String MERCHANT_NO = "810004816000153";//商户号,扫呗分配
    public static final String TERMINAL_ID = "12951873";//终端号,扫呗分配
    public static final String URL = "http://test2.lcsw.cn:8117/lcsw";  //测试接口地址

    /**
     * 聚合码支付（微信、支付宝等都能扫码支付）
     */
    public static SaobeiQrPayResponse qrpay(String accessToken, String merchantNo, String terminalId, String orderBody, String terminalTrace, String totalFee) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            //创建client
            SaobeiApiClient<SaobeiQrPayRequest,SaobeiQrPayResponse> client = new DefaultSaobeiApiClient<>(accessToken);
            //创建requst
            SaobeiQrPayRequest requst = new SaobeiQrPayRequest();
            requst.setPay_ver(PAY_VER);
            requst.setPay_type("000");
            requst.setService_id("016");
            requst.setMerchant_no(merchantNo);
            requst.setTerminal_id(terminalId);
            requst.setTerminal_trace(terminalTrace);
            requst.setTerminal_time(sdf.format(new Date()));
            requst.setTotal_fee(totalFee);
//            requst.setTotal_fee("1");
            requst.setOrder_body(orderBody);

//            requst.setNotify_url("https://www.kyz66.com/fubaihui/app/saobeiCallback");
            requst.setNotify_url("https://kyz.fbhkj.com/app/saobeiCallback"); //LukasLi
            //发送请求
            log.debug("请求报文:"+JSON.toJSONString(requst));
            SaobeiQrPayResponse response = client.execute(requst);
            log.debug("返回报文:"+JSON.toJSONString(response));
            return response;
        } catch (Exception e) {
            log.error("支付接口调用时发生异常", e);
            SaobeiQrPayResponse result = new SaobeiQrPayResponse();
            result.setResult_code("02");
            result.setReturn_msg("扫呗接口调用时发生异常");
            return result;
        }
    }

    /**
     * 小程序支付（生成微信小程序预付款单）
     */
    public static SaobeiMiniPayResponse minipay(String accessToken, String merchantNo, String terminalId, String xcxAppId, String xcxOpenId, String orderBody, String terminalTrace, String totalFee) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            //创建client
            SaobeiApiClient<SaobeiMiniPayRequest,SaobeiMiniPayResponse> client = new DefaultSaobeiApiClient<>(accessToken);
            //创建requst
            SaobeiMiniPayRequest requst = new SaobeiMiniPayRequest();
            requst.setPay_ver(PAY_VER);
            requst.setPay_type("010");
            requst.setService_id("015");
            requst.setMerchant_no(merchantNo);
            requst.setTerminal_id(terminalId);
            requst.setTerminal_trace(terminalTrace);
            requst.setTerminal_time(sdf.format(new Date()));
            requst.setTotal_fee(totalFee);
//            requst.setTotal_fee("1");
            requst.setOpen_id(xcxOpenId);
            requst.setOrder_body(orderBody);
//            requst.setNotify_url("https://www.kyz66.com/fubaihui/app/saobeiCallback");
            requst.setNotify_url("https://kyz.fbhkj.com/app/saobeiCallback"); //LukasLi
            requst.setSub_appid(xcxAppId);
            //发送请求
            log.debug("请求报文:"+JSON.toJSONString(requst));
            SaobeiMiniPayResponse response = client.execute(requst);
            log.debug("返回报文:"+JSON.toJSONString(response));
            return response;
        } catch (Exception e) {
            log.error("支付接口调用时发生异常", e);
            SaobeiMiniPayResponse result = new SaobeiMiniPayResponse();
            result.setResult_code("02");
            result.setReturn_msg("扫呗接口调用时发生异常");
            return result;
        }
    }

    /**
     * 付款码支付（扫码枪）
     */
    public static SaobeiBarcodePayResponse barcodepay(String accessToken, String merchantNo, String terminalId, String authNo, String terminalTrace, String totalFee) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            //创建client
            SaobeiApiClient<SaobeiBarcodePayRequest,SaobeiBarcodePayResponse> client = new DefaultSaobeiApiClient<>(accessToken);
            //创建requst
            SaobeiBarcodePayRequest requst = new SaobeiBarcodePayRequest();
            requst.setPay_ver(PAY_VER);
            requst.setPay_type("000");
            requst.setService_id("010");
            requst.setMerchant_no(merchantNo);
            requst.setTerminal_id(terminalId);
            requst.setTerminal_trace(terminalTrace);
            requst.setTerminal_time(sdf.format(new Date()));
            requst.setAuth_no(authNo);// 扫码枪扫到的用户的微信、支付宝等付款码数字
            requst.setTotal_fee(totalFee);
//            requst.setTotal_fee("1");
            //发送请求
            log.debug("请求报文:"+JSON.toJSONString(requst));
            SaobeiBarcodePayResponse response = client.execute(requst);
            log.debug("返回报文:"+JSON.toJSONString(response));
            return response;
        } catch (Exception e) {
            log.error("支付接口调用时发生异常", e);
            SaobeiBarcodePayResponse result = new SaobeiBarcodePayResponse();
            result.setResult_code("02");
            result.setReturn_msg("扫呗接口调用时发生异常");
            return result;
        }
    }

    /**
     * 订单查询（扫码枪场景，若扫码枪支付返回值code是03，则5秒轮训一次该接口，直到返回值code为01或02）
     */
    public static SaobeiTradeQueryResponse query(String accessToken, String merchantNo, String terminalId, String outTradeNo) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            //创建client
            SaobeiApiClient<SaobeiTradeQueryRequest,SaobeiTradeQueryResponse> client = new DefaultSaobeiApiClient<>(accessToken);
            //创建requst
            SaobeiTradeQueryRequest requst = new SaobeiTradeQueryRequest();
            requst.setPay_ver(PAY_VER);
            requst.setPay_type("000");
            requst.setService_id("020");
            requst.setMerchant_no(merchantNo);
            requst.setTerminal_id(terminalId);
            requst.setTerminal_trace("202003252204310000");// 无用，使用outTradeNo作为唯一标识
            requst.setTerminal_time("20200325220431");// 无用，使用outTradeNo作为唯一标识
            requst.setOut_trade_no(outTradeNo);
            //发送请求
            System.out.println("请求报文:"+JSON.toJSONString(requst));
            SaobeiTradeQueryResponse response = client.execute(requst);
            System.out.println("返回报文:"+JSON.toJSONString(response));
            return response;
        } catch (Exception e) {
            log.error("支付接口调用时发生异常", e);
            SaobeiTradeQueryResponse result = new SaobeiTradeQueryResponse();
            result.setResult_code("02");
            result.setReturn_msg("扫呗接口调用时发生异常");
            return result;
        }
    }

    public static void main(String[] args) {
//        minipay(ACCESS_TOKEN, MERCHANT_NO, TERMINAL_ID, "wxf9e3094d80bfe883", "or12A5LMxPYYkDFPh2jPkOQPtnsk", "sdk测试", "202003252204310000", "1");
//        qrpay(ACCESS_TOKEN, MERCHANT_NO, TERMINAL_ID, "sdk测试", "202003252204310000", "1");
//        barcodepay(ACCESS_TOKEN, MERCHANT_NO, TERMINAL_ID, "130297660446183202", "202003252204310000", "1");
//        query(ACCESS_TOKEN, MERCHANT_NO, TERMINAL_ID, "129518737721122052800170700785");
    }

}
